package com.iecas.handler;

import cn.hutool.core.util.ObjectUtil;
import com.iecas.context.GlobalContext;
import com.iecas.context.ServerContext;
import com.iecas.entity.Tank;
import com.iecas.entity.User;
import com.iecas.enums.BizEnum;
import com.iecas.enums.ResponseEnum;
import com.iecas.launch.Client;
import com.iecas.launch.Server;
import com.iecas.request.JoinReq;
import com.iecas.request.Root;
import com.iecas.response.BaseResponse;
import com.iecas.response.JoinResp;
import com.iecas.utils.OnlineManager;
import com.iecas.utils.SocketChannelManager;

import java.nio.channels.SocketChannel;

public class JoinReqHandler extends BaseHandler {

    @Override
    BaseResponse handle(Root baseRequest, Server server, Client client, SocketChannel socketChannel) {
        JoinReq joinReq = (JoinReq) baseRequest;
        String token = joinReq.getToken();
        User user = OnlineManager.get(token);

        JoinResp joinResp = new JoinResp();
        if (ObjectUtil.isNull(user)) {
            joinResp.setStatus(ResponseEnum.ERROR.getCode());
            joinResp.setCode(BizEnum.HEART_BEAT_RESP.getCode());
            joinResp.setMsg("TOKEN 信息错误,无法找到对应用户");
        } else {
            joinResp.setStatus(ResponseEnum.SUCCESS.getCode());
            joinResp.setCode(BizEnum.HEART_BEAT_RESP.getCode());
            // 添加通道
            SocketChannelManager.add(socketChannel,token);
            // 添加一个TANK
            Tank random = Tank.random();
            random.setId(token);
            random.setToken(token);
            random.setUsername(user.getUsername());
            ServerContext serverContext = GlobalContext.getServerContext();
            serverContext.putTank(random);
        }
        return joinResp;
    }
}
